package com.yxw.live_vod_boot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yxw.live_vod_boot.dto.*;
import com.yxw.live_vod_boot.dto.fans.FansQueryDTO;
import com.yxw.live_vod_boot.dto.fans.ShopFollowQueryDTO;
import com.yxw.live_vod_boot.entity.*;
import com.yxw.live_vod_boot.feign.BillingSetupServiceClient;
import com.yxw.live_vod_boot.mapper.*;
import com.yxw.live_vod_boot.service.FileService;
import com.yxw.live_vod_boot.service.OnDemandVideoService;
import com.yxw.live_vod_boot.service.ShopService;
import com.yxw.live_vod_boot.service.SysNoticeService;
import com.yxw.live_vod_boot.utils.*;
import com.yxw.live_vod_boot.vo.*;
import com.yxw.live_vod_facade.constant.LiveShopConstant;
import com.yxw.live_vod_facade.dto.ShopAddDTO;
import com.yxw.live_vod_facade.dto.ShopExtendAddDTO;
import com.yxw.live_vod_facade.enums.NoticeTypeEnum;
import com.yxw.yxnet_cd_center.common.constant.CommonConstant;
import com.yxw.yxnet_cd_center.common.constant.RedisIdConstant;
import com.yxw.yxnet_cd_center.common.dto.PageVO;
import com.yxw.yxnet_cd_center.common.enums.ErrorCodeEnum;
import com.yxw.yxnet_cd_center.common.enums.FileClassifyEnum;
import com.yxw.yxnet_cd_center.common.exception.BaseException;
import com.yxw.yxnet_cd_center.common.utils.BaseDateTime;
import com.yxw.yxnet_cd_center.common.utils.BaseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author liuxin
 * @create 2023-11-16 15:23:14
 * @description 店铺管理
 */
@Slf4j
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, YxLiveShopEntity> implements ShopService {

    @Autowired
    private UploadSourceMaterialReviewMapper materialReviewMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private HuaWeiObsUtil huaWeiObsUtil;

    @Autowired
    private SysNoticeService sysNoticeService;

    @Autowired
    private FileService fileService;

    @Autowired
    private OnDemandApplyMapper onDemandApplyMapper;

    @Autowired
    private BillingSetupServiceClient billingSetupServiceClient;

    @Autowired
    private UserUtil userUtil;

    @Autowired
    private ShopExtendMapper extendMapper;

    @Autowired
    private OnDemandVideoService videoService;

    @Autowired
    private RedisManager redisManager;

    @Autowired
    private FansMapper fansMapper;

    @Autowired
    private LiveCommentMapper liveCommentMapper;

    @Autowired
    private YxLiveShopPunishMapper oYxLiveShopPunishMapper;

    @Autowired
    private YxLiveAppealMapper oYxLiveAppealMapper;

    /**
     * 添加店铺
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ShopExtendVo addShop(ShopAddDTO dto) {
        YxLiveShopEntity entity = new YxLiveShopEntity();
        BeanUtil.copyProperties(dto, entity);
        //生成视频号
        entity.setLiveCode(BaseDateTime.getLongDateTimeStringNoSlipt(new Date()));
        entity.setLiveCoin(BigDecimal.valueOf(0));
        entity.setWeddingCandies(BigDecimal.valueOf(0));
        entity.setStorage(new BigDecimal(1024 * 20));
        entity.setRemainStorage(new BigDecimal(1024 * 20));
        entity.setCreateTime(new Date());
        entity.setShopState(CommonConstant.TWO);
        entity.setAddress(dto.getAddress());
        entity.setStatus(CommonConstant.ZERO);
        entity.setVideoCenterPermission(CommonConstant.ZERO);
        baseMapper.insert(entity);
        ShopExtendVo vo = new ShopExtendVo();
        BeanUtils.copyProperties(entity, vo);
        return vo;
    }

    /**
     * 添加店铺扩展信息
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addShopExtend(ShopExtendAddDTO dto) {
        YxLiveShopExtendEntity entity = new YxLiveShopExtendEntity();
        BeanUtil.copyProperties(dto, entity);
        entity.setCreateTime(new Date());
        extendMapper.insert(entity);
    }

    /**
     * 修改店铺的状态
     * @param shopId
     * @param status
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateShopStatus(Long shopId, Integer status) {
        YxLiveShopEntity shop = baseMapper.selectById(shopId);
        if (shop != null && status != null){
            shop.setStatus(status);
            baseMapper.updateById(shop);
        }
    }

    /**
     * 店铺开通点播
     * @param dto
     * @return
     */
    @Override
    public ShopExtendVo permissionShop(PermissionShopDTO dto) {
        YxLiveShopEntity shop = shopMapper.selectById(dto.getShopId());
        if (shop == null){
            throw new BaseException("当前店铺不存在");
        }
        BaseResult onDemandSpaceSize = billingSetupServiceClient.getOnDemandSpaceSize();
        Object data = onDemandSpaceSize.getData();
        int onDemandSpace = 0;
        if (data != null){
            onDemandSpace = (Integer)data;
            shop.setRemainStorage(BigDecimal.valueOf(onDemandSpace));
        }
        shop.setVideoCenterPermission(CommonConstant.ONE);
        shopMapper.updateById(shop);
        YxOnDemandApplyEntity onDemandApply = new YxOnDemandApplyEntity();
        onDemandApply.setSpaceId(dto.getSpaceId());
        onDemandApply.setDemandCode(BaseDateTime.getLongDateTimeStringNoSlipt(new Date()));
        onDemandApply.setUserId(userUtil.getLoginUserVo().getUserId());
        onDemandApply.setUserName(userUtil.getLoginUserVo().getUserName());
        onDemandApply.setShopId(shop.getLiveShopId());
        onDemandApply.setShopName(shop.getShopName());
        if (dto.getApplyDuration() != null) {
            Calendar calendar = Calendar.getInstance();
            Date currentTime = calendar.getTime();
            calendar.add(Calendar.MINUTE, dto.getApplyDuration());
            Date endTime = calendar.getTime();
            onDemandApply.setApplyTimeStart(currentTime);
            onDemandApply.setApplyTimeEnd(endTime);
            onDemandApply.setApplyDuration(dto.getApplyDuration());
        }
        onDemandApply.setApplyDes(dto.getApplyDes());
        onDemandApply.setStatus(CommonConstant.TWO);
        onDemandApply.setSpaceSize(onDemandSpace);
        onDemandApply.setCreateTime(new Date());
        onDemandApplyMapper.insert(onDemandApply);
        ShopExtendVo vo = new ShopExtendVo();
        BeanUtil.copyProperties(shop, vo);
        return vo;
    }

    /**
     * 点击视频开通权限,同时设置背景图与个性签名
     * @param shopBackground
     * @param homepageDTO
     */
//    @Override
    @Transactional(rollbackFor = Exception.class)
    public void enableVideoPermissions(MultipartFile shopBackground, UploadHomepageDTO homepageDTO) {
        YxLiveShopEntity shop = shopMapper.selectById(homepageDTO.getShopId());
        if (shop == null) {
            throw new BaseException("店铺不存在");
        }
        if (shopBackground == null || shopBackground.isEmpty()) {
            shop.setShopBackground("默认图片");
        }
        if (homepageDTO.getSign() == null || homepageDTO.getSign().isEmpty()){
            shop.setSign("点击这里修改个性签名哟");
        }
        shopMapper.updateById(shop);
        PermissionShopDTO shopDTO = new PermissionShopDTO();
        shopDTO.setShopId(shop.getLiveShopId());
        permissionShop(shopDTO);
        if (shopBackground != null && homepageDTO.getSign() != null){
            UploadHomepageDTO dto = new UploadHomepageDTO();
            dto.setShopId(homepageDTO.getShopId());
            dto.setSign(homepageDTO.getSign());
            uploadBackgroundPic(shopBackground, dto);
            return;
        }
        if (shopBackground != null ){
            UploadHomepageDTO dto = new UploadHomepageDTO();
            dto.setShopId(homepageDTO.getShopId());
            uploadBackgroundPic(shopBackground, dto);
            return;
        }
        if (homepageDTO.getSign() != null){
            ShopBackgroundReviewDTO dto = new ShopBackgroundReviewDTO();
            dto.setHomepageDTO(homepageDTO);
            addShopHomePageReview(dto);
        }
    }

    /**
     * 上传店铺背景图
     * @param backgroundFile
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public UploadSourceMaterialReviewVO uploadBackgroundPic(MultipartFile backgroundFile, UploadHomepageDTO homepageDTO) {
        MultipartFile[] multipartFiles = new MultipartFile[]{backgroundFile};
        List<YxFileVo> yxFileVos = fileService.uploadFile(multipartFiles, homepageDTO.getShopId(), FileClassifyEnum.IMAGES_FILE.getCode(),"");
        ShopBackgroundReviewDTO dto = new ShopBackgroundReviewDTO();
        dto.setBackgroundFile(backgroundFile);
        dto.setBackgroundPath(yxFileVos.get(0).getFileUrl());
        dto.setBackgroundKey(yxFileVos.get(0).getObjectKey());
        dto.setHomepageDTO(homepageDTO);
        return addShopHomePageReview(dto);
    }

    /**
     * 添加店铺主页审核信息
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public UploadSourceMaterialReviewVO addShopHomePageReview(ShopBackgroundReviewDTO dto) {
        YxLiveShopEntity shop = shopMapper.selectById(dto.getHomepageDTO().getShopId());
        if (shop == null){
            throw new BaseException("店铺不存在");
        }
        MultipartFile backgroundFile = dto.getBackgroundFile();
        YxUploadSourceMaterialReviewEntity review = new YxUploadSourceMaterialReviewEntity();
        review.setMaterialName(backgroundFile.getOriginalFilename());
        review.setMaterialUrl(dto.getBackgroundPath());
        review.setShopId(shop.getLiveShopId());
        review.setShopName(shop.getShopName());
        review.setExamineStatus(CommonConstant.ZERO);
        review.setCreateTime(new Date());
        review.setMaterialKey(dto.getBackgroundKey());
        review.setSign(dto.getHomepageDTO().getSign());
        review.setUserId(shop.getUserId());
        review.setUserName(shop.getUserName());
        materialReviewMapper.insert(review);
        UploadSourceMaterialReviewVO vo = new UploadSourceMaterialReviewVO();
        BeanUtils.copyProperties(review,vo);
        return vo;
    }

    /**
     * 店铺主页审核处理
     * @param examineDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult isShopHomepageReview(ReviewExamineDTO examineDTO) {
        BaseResult baseResult = new BaseResult();
        // 校验审核意见是否为空
        if (null == examineDTO.getExamineStatus()) {
            throw new BaseException("请给出审核意见!");
        }
        // 如果审核状态为拒绝，校验审核描述是否为空
        if (2 == examineDTO.getExamineStatus()) {
            String examineDescribe = examineDTO.getExamineDescribe();
            if (examineDescribe == null || examineDescribe.isEmpty()) {
                throw new BaseException("审核失败,审核拒绝时,请给出具体的审核意见!");
            }
        }
        // 获取店铺主页审核信息
        Long materialId = examineDTO.getHomepageReviewId();
        YxUploadSourceMaterialReviewEntity homepageReview = materialReviewMapper.selectById(materialId);
        if (homepageReview == null) {
            throw new BaseException("审核失败,当前审核数据不存在!");
        }
        try {
            NoticeTypeEnum type=null;
            if (1 == examineDTO.getExamineStatus()) {
                // 审核通过
                homepageReview.setExamineStatus(1);
                homepageReview.setExamineTime(new Date());
                homepageReview.setExamineUserId(examineDTO.getUserId());
                homepageReview.setExamineUserName(examineDTO.getUsername());
                homepageReview.setExamineDescribe(examineDTO.getExamineDescribe());
                materialReviewMapper.updateById(homepageReview);
                LambdaUpdateWrapper<YxLiveShopEntity> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(YxLiveShopEntity::getLiveShopId, homepageReview.getShopId())
                        .set(StringUtils.isNotBlank(homepageReview.getMaterialUrl()), YxLiveShopEntity::getShopBackground, homepageReview.getMaterialUrl())
                        .set(StringUtils.isNotBlank(homepageReview.getSign()), YxLiveShopEntity::getSign, homepageReview.getSign())
                        .set(YxLiveShopEntity::getUpdateTime, new Date());
                baseMapper.update(null, updateWrapper);
                type=NoticeTypeEnum.HOME_PAGE_UPDATE_PASS;
            } else {
                // 审核拒绝
                homepageReview.setExamineStatus(2);
                homepageReview.setExamineTime(new Date());
                homepageReview.setExamineUserId(examineDTO.getUserId());
                homepageReview.setExamineUserName(examineDTO.getUsername());
                homepageReview.setExamineDescribe(examineDTO.getExamineDescribe());
                materialReviewMapper.updateById(homepageReview);
                type=NoticeTypeEnum.HOME_PAGE_UPDATE_REFSE;
            }
            try {
                // 发送审核系统消息
                SendInteractMsgDto msgDto=new SendInteractMsgDto();
                msgDto.setShopId(homepageReview.getShopId());
                msgDto.setShopName(homepageReview.getShopName());
                msgDto.setBussId(String.valueOf(homepageReview.getMaterialId()));
                msgDto.setType(type);
                sysNoticeService.sendNotice(msgDto);
            } catch (Exception e) {
                log.error("审核消息发送失败：==================================================>" + e.getMessage());
            }
            baseResult = BaseResult.doSuccess(null, "审核成功");

        } catch (Exception e) {
            log.error("审核异常信息==================================================>" + e.getMessage());
            baseResult = BaseResult.failed(ErrorCodeEnum.UNKNOWN_ERROR, "审核异常信息:" + e.getMessage());
        }
        return baseResult;
    }


    /**
     * 获取店铺主页审核详情
     * @param materialId
     * @return
     */
    @Override
    public UploadSourceMaterialReviewVO getShopHomePageReviewById(Long materialId) {
        YxUploadSourceMaterialReviewEntity materialReviewEntity = materialReviewMapper.selectById(materialId);
        UploadSourceMaterialReviewVO vo = new UploadSourceMaterialReviewVO();
        BeanUtils.copyProperties(materialReviewEntity, vo);
        return vo;
    }

    /**
     * 获取店铺主页审核信息列表
     * @param queryDTO
     * @return
     */
    @Override
    public PageVO<UploadSourceMaterialReviewVO> getShopHomePageReviewList(ShopHomepageReviewQueryDTO queryDTO) {
        Page<UploadSourceMaterialReviewVO> page = new Page<>(queryDTO.getCurrPage(),queryDTO.getPageSize());
        List<UploadSourceMaterialReviewVO> list = materialReviewMapper.getUploadSourceMaterialReview(page,queryDTO);
        return PageUtils.get(page, list);
    }

    /**
     * 获取店铺主页信息
     * @param shopId
     * @return
     */
    @Override
    public ShopHomePageVO getShopHomepage(Long shopId) {
        ShopHomePageVO shopHomePage = shopMapper.getShopHomePage(shopId);
        // 获取店铺总点赞数
        OndemandVideoQueryDTO queryDTO = new OndemandVideoQueryDTO();
        queryDTO.setShopId(shopId);
        PageVO<OnDemandVideoVo> videoVoPageVO = videoService.pageVideo(queryDTO);
        List<Long> videoIds = new ArrayList<>();
        for (OnDemandVideoVo vo : videoVoPageVO.getList()){
            videoIds.add(vo.getVideoId());
        }
        int shopCnt = 0;
        for (Long videoId : videoIds) {
            Object obj = redisManager.get(RedisIdConstant.ON_DEMAND_VIDEO_LIKE_CNT + ":" + videoId);
            if (obj instanceof Integer) {
                int videoCnt = (Integer) obj;
                shopCnt += videoCnt;
            }
        }
        shopHomePage.setTotalLikeCount(shopCnt);
        // 获取店铺作品数
        shopHomePage.setVideoCount(videoVoPageVO.getList().size());
        // 获取店铺总关注数
        ShopFollowQueryDTO followQueryDTO = new ShopFollowQueryDTO();
        Page<YxFansEntity> page1 = new Page<>(followQueryDTO.getCurrPage(), followQueryDTO.getPageSize());
        List<ShopFollowListVO> followList = fansMapper.getShopFollowListByShopId(page1, shopId);
        if (followList != null && !followList.isEmpty()) {
            shopHomePage.setFollowerCount(followList.size());
        }else {
            shopHomePage.setFollowerCount(CommonConstant.ZERO);
        }
        // 获取店铺总粉丝量
        FansQueryDTO fansQueryDTO = new FansQueryDTO();
        Page<YxFansEntity> page2 = new Page<>(fansQueryDTO.getCurrPage(), fansQueryDTO.getPageSize());
        List<FansListVO> fansList = fansMapper.getFansListByShopId(page2, shopId);
        if (fansList != null && !fansList.isEmpty()){
            shopHomePage.setFanCount(fansList.size());
        }else {
            shopHomePage.setFanCount(CommonConstant.ZERO);
        }
        // 获取店铺拉黑用户数
        List<LiveBannedUserVO> list = getBannedUserListByShop(shopId);
        shopHomePage.setBlockUserCount(list.size());
        // 获取店铺直播相关状态
        Object mapValue = redisManager.getMapValue(LiveShopConstant.LIVE_SHOP_ONLINELIVE_SHOPIDKEY_HASH_REDISKEY, shopId.toString());
        if (mapValue != null){
            shopHomePage.setLiveStatus(CommonConstant.ONE);
        }else {
            shopHomePage.setLiveStatus(CommonConstant.ZERO);
        }
        // 获取店铺违规次数
        LambdaQueryWrapper<YxLiveShopPunishEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(true, YxLiveShopPunishEntity::getShopId, shopId);
        Integer violations = oYxLiveShopPunishMapper.selectCount(queryWrapper);
        shopHomePage.setViolationsCount(violations);
        // 获取店铺申述次数
        LambdaQueryWrapper<YxLiveAppealEntity> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(true, YxLiveAppealEntity::getShopId, shopId);
        Integer appealCount = oYxLiveAppealMapper.selectCount(queryWrapper1);
        shopHomePage.setAppealCount(appealCount);
        // 获取店铺直播间被封禁天数
        if (shopHomePage.getShopState() == 0){
            List<YxLiveShopPunishEntity> punishList = oYxLiveShopPunishMapper.selectList(queryWrapper);
            String punishUnit = punishList.get(0).getPunishUnit();
            Integer punishQuantity = punishList.get(0).getPunishQuantity();
            if (Integer.parseInt(punishUnit) == 2){
                shopHomePage.setBannedTime(punishQuantity);
            }
        }
        return shopHomePage;
    }

    /**
     * 修改店铺主页信息
     * @param shopBackground
     * @param homepageDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateShopHomepage(MultipartFile shopBackground, UploadHomepageDTO homepageDTO) {
        if (StringUtils.isEmpty((CharSequence) shopBackground) && StringUtils.isEmpty(homepageDTO.getSign())) {
            throw new IllegalArgumentException("个性签名和背景图不可同时为空");
        }
        // 判断店铺是否存在
        YxLiveShopEntity shop = baseMapper.selectById(homepageDTO.getShopId());
        if (shop == null) {
            throw new BaseException("店铺不存在！");
        }
        // 上传需要修改的背景图
        if (shopBackground != null || homepageDTO.getSign() != null){
            ShopBackgroundReviewDTO dto = new ShopBackgroundReviewDTO();
            UploadSourceMaterialReviewVO vo = null;
            if (StringUtils.isEmpty((CharSequence) shopBackground)){
                vo = uploadBackgroundPic(shopBackground, homepageDTO);
                dto.setBackgroundFile(shopBackground);
            }
            if (vo != null){
                dto.setBackgroundKey(vo.getMaterialKey());
                dto.setBackgroundPath(vo.getMaterialUrl());
            }
            dto.setHomepageDTO(homepageDTO);
            addShopHomePageReview(dto);
        }
    }

    /**
     * 修改店铺信息
     * @param shopId
     * @param shopAvatar
     * @param shopName
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateShopInformation(Long shopId, MultipartFile shopAvatar, String shopName) {
        if (shopAvatar == null && shopName == null){
            throw new BaseException("店铺头像与店铺名称修改不能同时为空");
        }
        // 判断店铺是否存在
        YxLiveShopEntity shop = baseMapper.selectById(shopId);
        if (shop == null) {
            throw new BaseException("店铺不存在！");
        }
        List<YxFileVo> yxFileVos= null;
        if (shopAvatar != null && shopAvatar.isEmpty()){
            String result = "";
            if (shop.getShopAvatar() != null) {
                result = shop.getShopAvatar().substring(shop.getShopAvatar().indexOf("images"));
                //删除华为云文件
                huaWeiObsUtil.deleteFile(result);
            }
            //上传头像
            MultipartFile[] multipartFiles = new MultipartFile[]{shopAvatar};
            yxFileVos = fileService.uploadFile(multipartFiles, shopId, FileClassifyEnum.IMAGES_FILE.getCode(),"");
        }
        // 构建修改条件
        LambdaUpdateWrapper<YxLiveShopEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(YxLiveShopEntity::getLiveShopId, shopId)
                .set(StringUtils.isNotBlank(shopName), YxLiveShopEntity::getShopName, shopName)
                .set(YxLiveShopEntity::getUpdateTime, new Date());
        if (yxFileVos != null){
            updateWrapper.set(true, YxLiveShopEntity::getShopAvatar, yxFileVos.get(0).getFileUrl());
        }
        // 执行修改操作
        int rows = baseMapper.update(null, updateWrapper);
        if (rows != 1) {
            throw new BaseException("修改店铺信息失败，服务器忙，请稍后尝试！");
        }
    }

    /**
     * 获取店铺列表(分页)
     * @param queryDTO
     * @return
     */
    @Override
    public PageVO<ShopHomePageVO> getShopList(ShopQueryDTO queryDTO) {
        Page<ShopHomePageVO> page = new Page<>(queryDTO.getCurrPage(),queryDTO.getPageSize());
        List<ShopHomePageVO> list = shopMapper.getShopHomePageList(page,queryDTO);
        return PageUtils.get(page, list);
    }

    /**
     * 获取店铺列表
     * @return
     */
    @Override
    public List<ShopHomePageVO> getAll() {
        return shopMapper.getShopList();
    }

    @Override
    public List<LiveBannedUserVO> getBannedUserListByShop(Long shopId) {
        return liveCommentMapper.getBannedUserListByShop(shopId);
    }

}
